//package com.school.edupoint.interceptor;
//
//
//import com.school.edupoint.config.EduContext;
//import com.school.edupoint.token.TokenManager;
//import jakarta.servlet.http.HttpServletRequest;
//import jakarta.servlet.http.HttpServletResponse;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.stereotype.Component;
//import org.springframework.web.servlet.HandlerInterceptor;
//
//
//@Component
//public class TokenInterceptor implements HandlerInterceptor {
//    @Autowired
//    private EduContext eduContext;
//
//    @Autowired
//    private RedisTemplate redisTemplate;
//
//
//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//
//        // 放行OPTIONS请求（跨域预检）
//        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
//            return true;
//        }
//
//        String token = request.getHeader("Authorization");
//        if (token == null || token.isBlank()) {
//            throw new Exception("未授权,无法访问");
//        }
//
//        String[] types = token.split(" ");
//        if (types[0].equals("pc")) {
//            if (!TokenManager.TOKEN_MAP.containsKey(types[1])) {
//                throw new Exception("未授权,无法访问");
//            }
//
//            // 可以把用户信息放到Context，方便controller用
//            eduContext.setUser(TokenManager.get(types[1]));
//            eduContext.setToken(token);
//        } else {
//            if (!TokenManager.TOKEN_STUDENT_MAP.containsKey(types[1])) {
//                throw new Exception("未授权,无法访问");
//            }
//
//            // 可以把用户信息放到Context，方便controller用
//            eduContext.setStudent(TokenManager.getStudent(types[1]));
//            eduContext.setToken(token);
//        }
//
//        return true;
//    }
//}
package com.school.edupoint.interceptor;

import com.school.edupoint.config.EduContext;
import com.school.edupoint.token.TokenManager;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 拦截请求并验证 Token 合法性
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private EduContext eduContext;

    @Autowired
    private TokenManager tokenManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行 OPTIONS 请求（跨域预检）
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }

        String tokenHeader = request.getHeader("Authorization");
        if (tokenHeader == null || tokenHeader.isBlank()) {
            throw new RuntimeException("未授权，无法访问");
        }

        String[] tokenParts = tokenHeader.split(" ");
        if (tokenParts.length != 2) {
            throw new RuntimeException("token 格式错误");
        }

        String tokenType = tokenParts[0];
        String actualToken = tokenParts[1];
        System.out.println("此时登录类型："+tokenType);
        if ("pc".equals(tokenType)) {
            if (!tokenManager.containsUserToken(actualToken)) {
                throw new RuntimeException("无效或过期的 token");
            }
            eduContext.setUser(tokenManager.get(actualToken));
            System.out.println("PC的eduContext.user为："+eduContext.getUser().getId());
        } else if ("student".equals(tokenType)) {
            if (!tokenManager.containsStudentToken(actualToken)) {
                throw new RuntimeException("无效或过期的 token");
            }
            eduContext.setStudent(tokenManager.getStudent(actualToken));
            System.out.println("PC的eduContext.student为："+eduContext.getStudent().getId());
        } else {
            throw new RuntimeException("不支持的 token 类型");
        }

        // 将原始 token 设置到上下文中
        eduContext.setToken(tokenHeader);

        return true;
    }

//    /**
//     * 在请求完成后清理线程变量，避免线程复用污染数据
//     */
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        eduContext.clear();
//    }
}